package sgi.client;
import java.io.IOException;
import java.util.Iterator;

import javax.swing.JOptionPane;

import sgi.details_new.ImageDetails;
import sgi.message.MessageSearch;

public class SGISearchArchiveController extends SGIController {
	
	private static SGISearchArchiveController search;
	private static SGISearchArchiveUI searchUI;
	
	public static SGISearchArchiveController create() throws IOException
	{
		if(SGISearchArchiveController.search == null)
		{
			SGISearchArchiveController.search = new SGISearchArchiveController();
			SGISearchArchiveController.searchUI.setController(search);
		}
		
		searchUI.setVisible(true);
		return search;
	}
	
	
	private SGISearchArchiveController()
	{
		searchUI = new SGISearchArchiveUI();
	}
	
	public void search(String dateFrom,String dateTo,String location)
	{
		MessageSearch msg = new MessageSearch(dateFrom,dateTo,location);
		sendSearch(msg);
	}
	
	public void search(String dateFrom,String dateTo)
	{
		MessageSearch msg = new MessageSearch(dateFrom,dateTo);
		msg.setSearchMessageType(1);
		sendSearch(msg);
	}
	
	
	private void sendSearch(MessageSearch msg)
	{
		SGISearchArchiveController.searchUI.clearTable();
		try {
			(SGIClientConnectionController.createConnection()).handleMessageFromClientUI(msg);
		} catch  (IOException e) {e.printStackTrace();}
	}
	
	public static void terminate()
	{
		SGISearchArchiveController.search = null;
		SGISearchArchiveController.searchUI.setController(null);
		SGISearchArchiveController.searchUI.setVisible(false);
		SGISearchArchiveController.searchUI = null;
	}
	
	@Override
	void handleMessage(Object msg) {
		if(((MessageSearch)msg).getImages() == null)
			JOptionPane.showMessageDialog(SGISearchArchiveController.searchUI,"Search completed. No results.");
		else
		{
			Iterator<ImageDetails> iterator = (((MessageSearch)msg).getImages()).iterator();
			SGISearchArchiveController.searchUI.clearTable();
			while (iterator.hasNext()) {
				SGISearchArchiveController.searchUI.addRow(iterator.next());
			} 
		}
	}
	
	public static SGISearchArchiveUI getUI()
	{
		return searchUI;
	}
}
